package com.stone.db.jdbc.algorithm;

import com.dangdang.ddframe.rdb.sharding.api.ShardingValue;
import com.dangdang.ddframe.rdb.sharding.api.strategy.table.SingleKeyTableShardingAlgorithm;
import com.google.common.collect.Range;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;

/**
 * <p>Created with IntelliJ IDEA. </p>
 * <p>User: Stony </p>
 * <p>Date: 2016/6/27 </p>
 * <p>Time: 17:47 </p>
 * <p>Version: 1.0 </p>
 */
public class DateTableShardingAlgorithm implements SingleKeyTableShardingAlgorithm<Date> {


    static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy_MM_dd");

    @Override
    public String doEqualSharding(Collection<String> availableTargetNames, ShardingValue<Date> shardingValue) {
        String name = SIMPLE_DATE_FORMAT.format(shardingValue.getValue());
//        for (String each : availableTargetNames) {
//            if (each.endsWith(name)) {
//                return each;
//            }
//        }
        return shardingValue.getLogicTableName()  + "_" + name;
//        throw new UnsupportedOperationException();
    }

    @Override
    public Collection<String> doInSharding(Collection<String> availableTargetNames, ShardingValue<Date> shardingValue) {
        Collection<String> result = new LinkedHashSet<>(availableTargetNames.size());
        Collection<Date> values = shardingValue.getValues();
        for (Date value : values) {
            String name = SIMPLE_DATE_FORMAT.format(value);
            for (String tableNames : availableTargetNames) {
                if (tableNames.endsWith(name)) {
                    result.add(tableNames);
                }
            }
        }
        return result;
    }

    @Override
    public Collection<String> doBetweenSharding(Collection<String> availableTargetNames, ShardingValue<Date> shardingValue) {
        Collection<String> result = new LinkedHashSet<>(availableTargetNames.size());
//        Range<Date> range = shardingValue.getValueRange();
//        for (Date i = range.lowerEndpoint(); i <= range.upperEndpoint(); i++) {
//            for (String each : availableTargetNames) {
//                if (each.endsWith(i % 2 + "")) {
//                    result.add(each);
//                }
//            }
//        }
        return result;
    }
}
